#include "OpReplace.h"
#include "Qt3DPicker.h"
#include "Ent.h"
#include "Registry.h"
#include "ActorTable.h"

class OpReplacePrivate
{
public:
	std::vector<std::shared_ptr<Ent>> m_olds;
	std::vector<std::shared_ptr<Ent>> m_news;
};

OpReplace::OpReplace(const std::vector<std::shared_ptr<Ent>>& olds,
	const std::vector<std::shared_ptr<Ent>>& news,
	QUndoCommand *parent)
	: Op(parent)
	, d_ptr(new OpReplacePrivate)
{
	d_ptr->m_olds = olds;
	d_ptr->m_news = news;
}

OpReplace::~OpReplace()
{
	delete d_ptr;
}

#include "QtOSGWidget.h"

void Replace(const std::vector<std::shared_ptr<Ent>>& olds,
	const std::vector<std::shared_ptr<Ent>>& news)
{
	Registry &reg = Registry::instance();
	auto widget3D = reg.get<QtOSGWidget>(widget3DID);
	widget3D->pauseRenderThread();

	// 如果对象很多，信号会被调用很多次，导致程序长时间无响应
	widget3D->getPicker()->blockSignals(true);
	for (auto p : olds)
	{
		auto parent = p->getParent();
		assert(parent);
		if (parent)
		{
			parent->removeChild(p);
		}
	}

	for (auto p : news)
	{
		auto parent = p->getParent();
		assert(parent);
		if (parent)
		{
			parent->addChild(p);
		}
	}
	// 发出一次消息
	widget3D->getPicker()->blockSignals(false);
	widget3D->getPicker()->userFeedback();

	widget3D->resumeRenderThread();
}

void OpReplace::redo()
{
	Replace(d_ptr->m_olds, d_ptr->m_news);
}

void OpReplace::undo()
{
	Replace(d_ptr->m_news, d_ptr->m_olds);
}
